package com.tbm.impl.json;

import com.tbm.base.controller.BaseController;
import com.tbm.base.service.MenuService;
import com.tbm.base.service.RoleService;
import com.tbm.base.service.SystemUserService;
import com.tbm.common.aspect.HttpAspect;
import com.tbm.common.util.PageData;
import com.tbm.common.util.RightsHelper;
import com.tbm.entity.MenuEntity;
import com.tbm.entity.RoleEntity;
import com.tbm.entity.SystemUser;
import net.sf.json.JSONArray;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员管理--模块
 *
 */
@RestController
public class AdminManagementControllerJson extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private SystemUserService systemUserService;


    /**
     * 角色查询Json
     * @return
     */
    @RequestMapping(value = "/admin-role-query")
    public Map<String,Object> adminRoleQuery(){
        Map<String ,Object> map = new HashMap<String, Object>();
        List<MenuEntity> menuList = menuService.findByParentId("0");
        List<RoleEntity> roleList = roleService.findAll();
        List<PageData> pageDataList = new ArrayList<PageData>();
        for(RoleEntity roleEntity : roleList){
            String rights = roleEntity.getRights();
            PageData parentPd = new PageData();
            parentPd.put("id",String.valueOf(roleEntity.getRoleId()));
            parentPd.put("region",roleEntity.getRoleName());
            parentPd.put("f1",roleEntity.getAddQx());
            parentPd.put("f2",roleEntity.getDelQx());
            parentPd.put("f3",roleEntity.getEditQx());
            parentPd.put("f4",roleEntity.getQueryQx());
            parentPd.put("iconCls","icon-man");
            parentPd.put("state","closed");
            pageDataList.add(parentPd);
            for(MenuEntity menuEntity : menuList){
                int menuId = menuEntity.getMenuId();
                //根目录在角色中
                if(RightsHelper.testRights(rights,menuId)){
                    List<MenuEntity> menuSonList = menuService.findByParentId(String.valueOf(menuId));
                    PageData parent1Pd = new PageData();
                    parent1Pd.put("id",String.valueOf(roleEntity.getRoleId())+String.valueOf(menuId));
                    parent1Pd.put("region",menuEntity.getMenuName());
                    parent1Pd.put("_parentId",roleEntity.getRoleId());
                    parent1Pd.put("state","closed");
                    pageDataList.add(parent1Pd);
                    for(MenuEntity menuSonEntity : menuSonList){
                        int menuSonId = menuSonEntity.getMenuId();
                        if(RightsHelper.testRights(rights,menuSonId)){
                            PageData sonpd = new PageData();
                            sonpd.put("id",String.valueOf(menuSonId)+String.valueOf(menuId)+String.valueOf(roleEntity.getRoleId()));
                            sonpd.put("region",menuSonEntity.getMenuName());
                            sonpd.put("_parentId",String.valueOf(roleEntity.getRoleId())+String.valueOf(menuId));
                            pageDataList.add(sonpd);
                        }
                    }
                    //根目录不在角色中
                }else{

                }
            }
        }
        map.put("rows", JSONArray.fromObject(pageDataList));
        return  map;
    }


    @RequestMapping(value = "/admin-list-roleId-roleName")
    public Map<String ,Object> adminListRoleIdRoleName(){
        PageData pageData = this.getPageData();
        int roleId = pageData.get("roleId")==null?-1:Integer.valueOf(pageData.get("roleId").toString());
        RoleEntity roleEntity = roleService.findOne(roleId);
        String roleName = roleEntity.getRoleName();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("roleName",roleName);
        return map;
    }

    /**
     * 角色管理--新增角色
     * @return
     */
    @Transactional
    @RequestMapping(value = "/admin-role-list-insert")
    public Object adminRoleListInsert(){
        PageData pageData = this.getPageData();
        String roleName = pageData.get("role_name")==null?"":pageData.get("role_name").toString();
        String addQx = pageData.get("add_qx")==null?"":pageData.get("add_qx").toString();
        String delQx = pageData.get("del_qx")==null?"":pageData.get("del_qx").toString();
        String editQx = pageData.get("edit_qx")==null?"":pageData.get("edit_qx").toString();
        String queryQx = pageData.get("cha_qx")==null?"":pageData.get("cha_qx").toString();
        String roleMarks = pageData.get("role_marks")==null?"":pageData.get("role_marks").toString();

        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setRoleName(roleName);
        roleEntity.setRights("0");
        roleEntity.setAddQx(addQx);
        roleEntity.setDelQx(delQx);
        roleEntity.setEditQx(editQx);
        roleEntity.setQueryQx(queryQx);
        roleEntity.setRemarks(roleMarks);
        roleService.save(roleEntity);
        return null;
    }

    /**
     * 角色管理--修改角色
     * @return
     */
    @Transactional
    @RequestMapping(value = "/admin-role-list-update")
    public Object adminRoleListUpdate(){
        PageData pageData = this.getPageData();
        String roleId = pageData.get("role_id")==null?"":pageData.get("role_id").toString();
        String roleName = pageData.get("role_name")==null?"":pageData.get("role_name").toString();
        String addQx = pageData.get("add_qx")==null?"":pageData.get("add_qx").toString();
        String delQx = pageData.get("del_qx")==null?"":pageData.get("del_qx").toString();
        String editQx = pageData.get("edit_qx")==null?"":pageData.get("edit_qx").toString();
        String queryQx = pageData.get("cha_qx")==null?"":pageData.get("cha_qx").toString();
        String roleMarks = pageData.get("role_marks")==null?"":pageData.get("role_marks").toString();

        //获取需要Update的
        RoleEntity roleEntity = roleService.findOne(Integer.valueOf(roleId));
        roleEntity.setRoleName(roleName);
        roleEntity.setAddQx(addQx);
        roleEntity.setDelQx(delQx);
        roleEntity.setEditQx(editQx);
        roleEntity.setQueryQx(queryQx);
        roleEntity.setRemarks(roleMarks);
        roleService.saveAndFlush(roleEntity);
        return null;
    }

    /**
     * 角色管理--删除角色
     * @return
     */
    @Transactional
    @RequestMapping(value = "/admin-role-delete")
    public Object adminRoleDelete(){
        PageData pageData = this.getPageData();
        int roleId = pageData.get("roleID")==null?-1:Integer.valueOf(pageData.get("roleID").toString());
        if(roleId!=-1){
            roleService.delete(roleId);
        }
        return null;
    }

    /**
     * 角色管理--分配角色
     * @return
     */
    @Transactional
    @RequestMapping(value = "/admin-role-assign")
    public Object adminRoleAssign(){
        PageData pageData = this.getPageData();
        String rights = pageData.get("rights")==null?"":pageData.get("rights").toString();
        rights = RightsHelper.sumRights(rights.split(",")).toString();
        int roleId = pageData.get("ID")==null?-1:Integer.valueOf(pageData.get("ID").toString());
        if(-1!=roleId){
            RoleEntity roleEntity = roleService.findOne(roleId);
            roleEntity.setRights(rights);
            roleService.saveAndFlush(roleEntity);
        }
        return null;
    }

    /**
     * 获取角色管理--角色列表
     * @return
     */
    @RequestMapping(value = "/admin-get-role-list")
    public Object adminGetRoleList(){
        List<PageData> pageDataList = new ArrayList<PageData>();
        List<RoleEntity> roleEntities = roleService.findAll();
        for(RoleEntity roleEntity : roleEntities){
            PageData pd = new PageData();
            pd.put("value",roleEntity.getRoleId());
            pd.put("text",roleEntity.getRoleName());
            pageDataList.add(pd);
        }
        return JSONArray.fromObject(pageDataList);
    }

    /**
     * 用户删除
     * @return
     */
    @Transactional
    @RequestMapping(value = "/admin-delete-user_id")
    public Object adminDeleteUserId(){
        PageData pageData = this.getPageData();
        int userId = pageData.get("userId")==null?-1:Integer.valueOf(pageData.get("userId").toString());
        systemUserService.delete(userId);
        return null;
    }

    //激活用户
    @Transactional
    @RequestMapping(value = "/admin-active-user_id")
    public Object adminActiveUserId(){

        PageData pageData = this.getPageData();
        int userId = pageData.get("userId")==null?-1:Integer.valueOf(pageData.get("userId").toString());
        SystemUser systemUser = systemUserService.findOne(userId);
        systemUser.setIsLock("Y");
        systemUserService.saveAndFlush(systemUser);
        return null;
    }

    /**
     * 管理员-新增
     * @return
     */
    @Transactional
    @RequestMapping(value = "/admin-insert")
    public Object adminInsert(){
        PageData pageData = this.getPageData();
        String userName = pageData.get("userName")==null?"":pageData.get("userName").toString();
        String dispalyName = pageData.get("displayName")==null?"":pageData.get("displayName").toString();
        String roleId = pageData.get("roleId")==null?"":pageData.get("roleId").toString();
        SystemUser systemUser = new SystemUser();
        systemUser.setUserName(userName);
        systemUser.setPassword(new SimpleHash("MD5", "123456", userName, 1024).toString());
        systemUser.setDisplayName(dispalyName);
        systemUser.setRoleId(roleId);
        systemUser.setIsLock("N");
        systemUserService.save(systemUser);
        return null;
    }

    /**
     * 管理员--修改
     * @return
     */
    @Transactional
    @RequestMapping(value = "/admin-update")
    public Object adminUpdate(){
        PageData pageData = this.getPageData();
        String dispalyName = pageData.get("displayName")==null?"":pageData.get("displayName").toString();
        String roleId = pageData.get("roleId")==null?"":pageData.get("roleId").toString();
        int userId = pageData.get("userId")==null?-1:Integer.valueOf(pageData.get("userId").toString());
        if(-1!=userId){
            SystemUser systemUser = systemUserService.findOne(userId);
            systemUser.setDisplayName(dispalyName);
            systemUser.setRoleId(roleId);
            systemUserService.saveAndFlush(systemUser);
        }
        return null;
    }

    @Transactional
    @RequestMapping(value = "/admin-menu-save")
    public Map<String,String> adminMenuSave(){
        PageData pageData = this.getPageData();
        Map<String,String> result = new HashMap<>();
        String name = pageData.get("name")==null?"":pageData.get("name").toString();
        String other = pageData.get("other")==null?"":pageData.get("other").toString();
        String flag = pageData.get("flag")==null?"":pageData.get("flag").toString();
        String parentId = pageData.get("parentId")==null?"":pageData.get("parentId").toString();
        if("".equals(name)){
            result.put("result","error");
            return result;
        }else{
            //ICON
            MenuEntity menuEntity = new MenuEntity();
            menuEntity.setMenuName(name);
            menuEntity.setParentId(parentId);
            menuEntity.setMenuOrder("0");
            menuEntity.setMenuType("1");
            if("N".equals(flag)){
                menuEntity.setMenuIcon(other);
                menuEntity.setMenuURL("#");
            //ROUT
            }else if("Y".equals(flag)){
                menuEntity.setMenuURL(other);
                menuEntity.setMenuIcon("#");

            }
            menuService.save(menuEntity);
            result.put("result","success");
            return result;
        }

    }


    @RequestMapping(value = "/initMenu" , produces = "application/json;charset=UTF-8")
    public Map<String,List<PageData>> initMenu(@RequestParam(required = false) String rights){
        Map<String,List<PageData>> map = new HashMap<String, List<PageData>>();

        MenuEntity menuEntityExample = new MenuEntity();
        menuEntityExample.setParentId("0");
        Example<MenuEntity> ex = Example.of(menuEntityExample);
        List<MenuEntity> allMenu = menuService.findAll(ex);
        List<PageData> result = new ArrayList<PageData>();
        result = this.getTreeMenu(allMenu);
        List<PageData> nodes = new ArrayList<PageData>();

        for(PageData tPageData : result ){
            if(tPageData.getString("PARENT_ID").equals("0")){
                int mu = Integer.valueOf(tPageData.get("MENU_ID").toString());
                PageData parentPD = new PageData();
                parentPD.put("id",mu);
                parentPD.put("pId",tPageData.getString("PARENT_ID"));
                parentPD.put("name",tPageData.getString("MENU_NAME"));
                parentPD.put("checked", RightsHelper.testRights(rights,mu));
                nodes.add(parentPD);
                List<MenuEntity> firstSubMenu = (List<MenuEntity>) tPageData.get("firstSubMenu");
                for(MenuEntity subPageData : firstSubMenu){
                    int smu = subPageData.getMenuId();
                    PageData firstPD = new PageData();
                    firstPD.put("id",smu);
                    firstPD.put("pId",subPageData.getParentId());
                    firstPD.put("name",subPageData.getMenuName());
                    firstPD.put("checked", RightsHelper.testRights(rights,smu));
                    nodes.add(firstPD);
                }
            }
        }
        map.put("nodes",nodes);
        return map;
    }

    public List<PageData> getTreeMenu(List<MenuEntity> menu){
        List<PageData> menuResult = new ArrayList<PageData>();
        for(MenuEntity parentPageData : menu){
            PageData temp = new PageData();
            MenuEntity menuEntityExample = new MenuEntity();
            menuEntityExample.setParentId(String.valueOf(parentPageData.getMenuId()));
            Example<MenuEntity> ex = Example.of(menuEntityExample);
            List<MenuEntity> firstSubMenu = menuService.findAll(ex);
            temp.put("MENU_ID",parentPageData.getMenuId());
            temp.put("MENU_NAME",parentPageData.getMenuName());
            temp.put("MENU_URL",parentPageData.getMenuURL());
            temp.put("PARENT_ID",parentPageData.getParentId());
            temp.put("MENU_ORDER",parentPageData.getMenuOrder());
            temp.put("MENU_ICON",parentPageData.getMenuIcon());
            temp.put("MENU_TYPE",parentPageData.getMenuType());
            temp.put("firstSubMenu",firstSubMenu);
            menuResult.add(temp);
        }
        return menuResult;
    }

}
